define(['config', 'text!app/module/system/businessList.html', 'laypage',
    'mydialog', 'autocomplete','jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
    mydialog, autocomplete,jqGrid,common, laydate) {
	
//	console.log("兄弟我不得不告诉你，这是个坑。保重，如果遇到问题请联系QQ383832246");
	
	var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/businessList";
    
    var grid_arr = new Array();
    
//    var businessId;
    
    var areaId;
    
    var num;
    
    var item = 0;

    var model = avalon.define({
    	$id : "businessList",
    	businessListInfo: {
    		id: "",
            name: "",
            level: "",
            areaId: "",
            describe:"",
            createTime:"",
            createUser: ""
    	},
         // 查询条件,
        name:"",
        businessId:"",
        query: {
        	 name:"",
        },
         statusArr: [],
         selected: [],
         roles: [],
         
         init: function () {
             model.loadGrid();
//             model_detail.loadAexgGrid();
             model.addEvent();
             model.loadGrid_d();
             model.loadGrid_r();
         },
         loadGrid: function () {
             function t(val, opt, row) {
                 
            	 var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="index.html#!/108"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
            	 return html_con;
             }
             
            
           var i = Public.setGrid();
             
             $("#grid").jqGrid({
                 loadBeforeSend: function (jqXHR) {
                     jqXHR.setRequestHeader("X-AuthToken", token);
                 },
                 datatype: "json",
                 mtype: "POST",
                 url: grid_url+"/list",
                 postData: model.query.$model,
                 loadComplete: function (data) {
                	 
                 },
                 loadError: function (xhr, status, error) {
                     alert(JSON.parse(xhr.responseText).msg);
                 },
                 colModel: [{
                         name: "operating",
                         label: "操作",
                         width: '5%',
                         formatter: t,
                     },
                     {
                         name: "id",
                         label: "id",
                         width: '12%',
                         hidden: true
                     },
                     {
                         name: "name",
                         label: "营业厅名称",
                         width: '12%',
                     },
                     {
                         name: "level",
                         label: "营业厅等级",
                         width: '10%',
                     },
                     {
                         name: "describes",
                         label: "描述",
                         width: '13%',
                         editable:true
                     },
                     {
                         name: "remarks",
                         label: "备注",
                         width: '10%',
                     },
                     {
                         name: "createTime",
//                         formatter:"date",
                 	     formatter: Public.custDatefmter,
//                         formatoptions: {srcformat:'u',newformat:'Y-m-d'},
                         label: "创建日期",
                         width: '13%',
                     }
                 ],
                 cmTemplate: {
                     sortable: false,
                     title: false,
                     align: "center"
                 },
                 //分页
                 page: 1,
                 rowNum: 10,
                 rowList: [10, 20, 30],
                 height: 300,
                 autowidth: true,
                 pager: '#page',
                 sortname: 'id',
                 viewrecords: true,
                 forceFit: false,
                 rownumbers: true,
                 multiselect: true,
                 multiboxonly: true,
                 sortorder: "desc",
                 /* 单击行数据   显示从表*/
                 onSelectRow: function(rowId) {
                	 
                	 console.log("点击获取："+rowId);
                     model.businessId = rowId;
                     model.reLoadGrid_d();

                 },
                 jsonReader: {
                     root: "data.list",
                     records: "data.totalRow",
                     total: "data.totalPage",
                     repeatitems: false,
                     id: "id"
                 },
                 loadError: function () {
                     parent.Public.tips({
                         type: 1,
                         content: "加载数据异常！"
                     })
                 }
             });

         },
        loadGrid_d: function () {
        	
        	
        	 /**grid中生成下达、查看按钮*/
            function a(val, opt, row) {
           	 var html_con ;
	            	 if(row.productionInstructionStatus == 0){
           		 html_con = '<div class="productionInstructionStatus" data-id="' + row.id + '"><a class = "view" id="detail"><span>添加设备</span></a></div>';

           	 }else if(row.productionInstructionStatus == 1){
           		 html_con = '<div class="productionInstructionStatus" data-id="' + row.id + '"><a class = "view" id="detail"><span>查看</span></a></div>';
           		 
           	 }
           	 return html_con;
            }
            
        	
            $("#grid_d").jqGrid({
                loadBeforeSend: function (jqXHR) {
                    jqXHR.setRequestHeader("X-AuthToken", token);
                },
                datatype: "json",
                url: grid_url+"/detailList",
                mtype: 'POST',
                postData: {
//                    "businessId" : model.id
                },
                loadComplete: function (data) {
               	 	console.log("1111111111111111111111111111111");
               	 	console.log("data:",data)
                },
                success: function () {
                },
                loadError: function (xhr, status, error) {
//                             alert(JSON.parse(xhr.responseText).msg);
                },
                colNames : ['id','areaId','功能区名称','是否模板','描述','备注','创建时间',],
                colModel : [
                    {name : 'id',index : 'id',width : 100,align : "right",hidden:true} ,
                    {name : 'areaId',index : 'areaId',width : 100,align : "right",hidden:true} ,
                    {name : 'name',index : 'name',width : 80},
                    {name : 'status',index : 'status',width : 80,align : "right",hidden:true},
                    {name : 'describe',index : 'describe',width : 180,align : "right",hidden:true} ,
                    {name : 'remarks',index : 'remarks',width : 80,align : "right"},
                    {name : 'createTime',index : 'createTime',width : 80,align : "right"}
                ],
                cmTemplate: {
                    sortable: false,
                    title: false
                },
                page: 1,
                rowNum: 10,
                rowList: [10, 20, 30],
                pager: '#page_d',
                sortname: 'id',
                viewrecords: true,
                forceFit: false,
                rownumbers: true,
                multiselect: true,
                multiboxonly: true,
                sortorder: "desc",
                autoScroll: false,
                height: 150,
                altRows: true,
                gridview: true,
                autowidth: true,
                onSelectRow: function(rowId) {
               	 
                	model.ids = $("#grid_d").jqGrid("getRowData", rowId).id;
                	var rowData = $("#grid_d").jqGrid('getRowData',rowId);
                	areaId = rowData.areaId;
                	console.log("点击获取rowId："+rowId);
                    console.log("点击获取ids："+model.ids);
//                    $("#grid_d").getCell(rowId,'areaId');
                    
                    console.log("点击获取rowData："+rowData);
                    console.log("点击获取areaId："+areaId);
                    model.reLoadGrid_r();
                },
                jsonReader: {
                    root: "data.data.list",
                    records: "data.totalRow",
                    total: "data.totalPage",
                },

            });
        },
        loadGrid_r: function () {
           $("#grid_r").jqGrid({
               loadBeforeSend: function (jqXHR) {
                   jqXHR.setRequestHeader("X-AuthToken", token);
               },
               datatype: "json",
               url: grid_url+"/getProductList",
               mtype: 'POST',
               postData: {
            	   "areaId":areaId,
            	   "businessId":model.businessId
               },
               loadComplete: function (data) {
              	 	console.log("1111111111111111111111111111111");
              	 	console.log("data:",data)
               },
               success: function () {
               },
               loadError: function (xhr, status, error) {
//                            alert(JSON.parse(xhr.responseText).msg);
               },
               colNames : ['id','设备名称','单价','数量','建议零售价','描述','备注','创建时间','创建人'],
               colModel : [
                   {name : 'id',index : 'id',width : 100,align : "right",hidden:true} ,
                   {name : 'productName',index : 'name',width : 80},
                   {name : 'floorPrice',index : 'floorPrice',width : 80},
                   {name : 'numb',index : 'numb',width : 80},
                   {name : 'retailPrice',index : 'retailPrice',width : 80},
                   {name : 'describe',index : 'describe',width : 180,align : "right",hidden:true} ,
                   {name : 'remarks',index : 'remarks',width : 80,align : "right"},
                   {name : 'createTime',index : 'createTime',width : 80,align : "right"},
                   {name : 'createUser',index : 'createUser',width : 80,align : "right"},
               ],
               cmTemplate: {
                   sortable: false,
                   title: false
               },
               page: 1,
               rowNum: 10,
               rowList: [10, 20, 30],
               pager: '#page_r',
               sortname: 'id',
               viewrecords: true,
               forceFit: false,
               rownumbers: true,
               multiselect: true,
               multiboxonly: true,
               sortorder: "desc",
               autoScroll: false,
               height: 150,
               altRows: true,
               gridview: true,
               autowidth: true,
               onSelectRow: function(rowId) {
                   model.id = $("#grid_r").jqGrid("getRowData", rowId).id;
                   console.log("点击获取："+model.id);
//                   model.reLoadGrid_r();
               },
               jsonReader: {
                   root: "data.data.list",
                   records: "data.totalRow",
                   total: "data.totalPage",
               },

           });
       },
        reLoadGrid: function () {
            $("#grid").jqGrid("setGridParam", {
            	url: grid_url+"/list",
                datatype : "json",
                mtype : "POST",
                page:1,
                postData:{
                    
                }
            }).trigger("reloadGrid");
        },
        reLoadGrid_d: function () {
            $("#grid_d").jqGrid("setGridParam", {
                url: grid_url+"/detailList",
                datatype : "json",
                mtype : "POST",
                page:1,
                postData:{
                    "businessId" : model.businessId
                }
            }).trigger("reloadGrid");
        },
        reLoadGrid_r: function () {
            $("#grid_r").jqGrid("setGridParam", {
                url: grid_url+"/getProductList",
                datatype : "json",
                mtype : "POST",
                page:1,
                postData:{
                    "areaId" : areaId,
                    "businessId" : model.businessId
                }
            }).trigger("reloadGrid");
        },
         reset: function () {
             model.query = {
                 name: ""
             };
             model.queryData();
         },
         queryData: function () {
             $("#grid").jqGrid("setGridParam", {
                 url: grid_url+"/list",
                 datatype: "json",
                 mtype: 'POST',
                 page:1,
                 postData: model.query.$model
             }).trigger("reloadGrid");
         },
         queryDialogData: function (){
        	 $("#grid").jqGrid("setGridParam", {
                 url: "/api/produce/list",
                 datatype: "json",
                 mtype: 'POST',
                 page:1,
                 postData: model.query.$model
             }).trigger("reloadGrid");
         },
         //下达生产指令
         Issued: function (rowData) {
        	 console.log("rowData",rowData);
        	 if(rowData.productionInstructionStatus == '已下达'){
            	 $.ajax({
            		 type:"POST",
            		 url:"/api/produce/list",
            		 data:{
            			 "orderNo":rowData.orderNo,
            		 },
            		 success: function (data) {
            			 console.log('[data1111111111111111111111111111]',data);
        				 model.productionInfo=data.data;
        				 console.log('[model.productionInfo]',model.productionInfo);
        				 model.productionInfo.startingDate = Public.custDatefmter(model.productionInfo.startingDate);
        				 
    					 $("#editUser input").attr("readOnly","true");
    					 $("#editUser textarea").attr("readOnly","true");
    					 $("#startingDate").removeAttr("onclick");
            		 },
            		 beforeSend: function (xhr) {
                         xhr.setRequestHeader("X-AuthToken", token);
                     },
                     error: function (responseData, textStatus, errorThrown) {
                         alert("Failed: " + responseData);
                     }
            	 });
        	 }else if(rowData.productionInstructionStatus ===''||rowData.productionInstructionStatus === 0){
        		 model.initproduction();
	        	 $.ajax({
	    			 type:"POST",
	                 url: "/api/produce/getProductionNo",
	                 success:function(data){
	                	 console.log('[data]',data);
	                	 model.initproduction();
	                	 productionNo = data;
	                	 model.productionInfo.productionNo=data;
	                 },

	                 beforeSend: function (xhr) {
	                     xhr.setRequestHeader("X-AuthToken", token);
	                 },
	                 error: function (responseData, textStatus, errorThrown) {
	                     alert("Failed: " + responseData);
	                 }
	    		 });
        	 }
             dialog({
                 title: '下达生产指令',
                 content: $('#editUser'),
                 okValue: "确定",
                 ok: function () {
                      if(model.productionInfo.orderNo!= ""){
                    	  return ;
                      }else{
	                    	  //非空校验
	                    	  if(($(".mustAdd").val())==null||($(".mustAdd").val())==""){
	                    		  alert("生产指令号不能为空！");
	                    	  }else{
                    		  model.productionInfo.orderNo=rowData.orderNo;
                    		  model.productionInfo.totalQuantity= rowData.totalQuantity;
                    		  
                    		  var map = {
                    				  production:model.productionInfo.$model,
                    				  arr:grid_arr
                    		  }
                    		  console.log("grid_arr");
                         	 if(item == 1){
                        		 dialog({
                                     title: "错误！",
                                     content: "请勿重复提交！",
                                     okValue: "确定",
                    	        	 ok: function (){
                    	        	 }
                            	 }).showModal();
                        		 return;  
                        	 }
                      	    $.ajax({
                                type: "POST",
                                 url: "/api/produce/save" ,
                                 contentType: "application/json;charset=utf-8",
                                 data:JSON.stringify(map),
                                 beforeSend: function (xhr) {
                                     xhr.setRequestHeader("X-AuthToken", token);
                                 },
                                 success: function (data) {
                                	 console.log("data",data);
                                	 if(data.success == false && data.status == 1){
                                		 dialog({
                                             title: "错误！",
                                             content: "物料库存不足，不能生产 ！",
                                             okValue: "确定",
                            	        	 ok: function (){
                            	        	 }
                                    	 }).showModal();
                                	 }else if(data.status == 0){
                                		 item = 1;
                                		 model.reLoadGrid();
                                		 dialog({
                                             title: "下达生产任务成功！",
                                             content: "下达生产任务成功！",
                                             okValue: "确定",
                            	        	 ok: function (){
                            	        	 }
                                    	 }).showModal();
                                	 }
                                 },
      	                           error: function (responseData, textStatus, errorThrown) {
                                     alert("系统异常");
                                 }
                             });
                    	  }
                    	  
                    	   }
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         
         /**审核订单*/
         examine:function(ids){
        	 console.log('this is [ids]````````',ids);
        	 dialog({
                 title: "确认操作",
                 content: "确定通过审核？ ",
                 okValue: "确定",
	        	 ok: function () {
	        		 $.ajax({
	        		 type:"POST",
	        		 url:"/api/order/toExamine",
	        		 data:{
	        			 "ids":ids
	        		 },
	        		 success: function () {
	        			 
	        			 model.reLoadGrid();
	        		 },
	        		 beforeSend: function (xhr) {
	                     xhr.setRequestHeader("X-AuthToken", token);
	                 },
	                 error: function (responseData, textStatus, errorThrown) {
	                     alert("Failed: " + responseData);
	                 }
	        	 });
	        	 },
	        	 cancelValue: "取消",
                 cancel: function () {} 
        	 }).showModal();
         },
         
         /**删除订单*/
         del: function (ids) {
             dialog({
                 title: "确认操作",
                 content: "确定删除？ 此操作不可恢复！",
                 okValue: "确定",
                 ok: function () {

                     $.ajax({
                         type: "POST",
                         url: "/api/order/delete",
                         data: {
                             "ids": ids
                         },
                         beforeSend: function (xhr) {
                             xhr.setRequestHeader("X-AuthToken", token);
                         },
                         success: function (data, status, xhr) {
                             if (data) {
                                 $('#grid').jqGrid('delRowData', ids);
                                 dialog({
                                     title: "删除成功",
                                     content: "删除成功！",
                                     okValue: "确定",
                                     ok: function () {
                                     },
                                     cancelValue: "取消",
                                     cancel: function () {}
                                 }).showModal();
                             }
                             model.queryData();
                         },
                         error: function (responseData, textStatus, errorThrown) {
                             alert("Failed: " + responseData);
                         }

                     });
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         addEvent: function () {
        	 
        	 /**打开新的table 跳转页面*/
        	 $(".fr").on("click", "#add", function (e) {
        		 top.topManager.openPage({
        			id:"addOrder",
        			title:"新建清单",
        			href:'index.html#!/108?businessId=',
        			reload:true
        		 })
        	 });
        	 
        	 var t = this;
        	 //修改订单信息
        	 $(".grid-wrap").on("click", ".fa-edit", function (e) {
                 var t = $(this).parent().data("id");
                 var rowData = $("#grid").jqGrid('getRowData',t);
                 var businessId = t;
//                 window.location.href='index.html#!/108?orderNo='+orderNo
                 top.topManager.openPage({
         			id:"addOrder",
         			title:"修改清单",
         			href:'index.html#!/108?businessId='+businessId,
         			reload:true
         		 })
             });
        	 
        	 /** 下达订单*/
             $(".grid-wrap").on("click", ".view", function (e) {
            	 var t = $(this).parent().data("id");
            	 var id = $("#grid").jqGrid("getGridParam", "selarrrow");
            	 var rowData = $("#grid").jqGrid('getRowData',id);
            	 console.log("111111111111111111111111111111111111111111111111",rowData);
            	 var orderNo = rowData.orderNo;
            	 console.log('this is [orderNo]::::',orderNo);
            	 /**dialog中显示子表*/
                 $("#grid_a").jqGrid({
                	 loadBeforeSend: function (jqXHR) {
                         jqXHR.setRequestHeader("X-AuthToken", token);
                     },
                     datatype: "json",
                     
                     url: grid_url+"/detailList",
                     mtype: 'POST',
                     cache:false,
                     postData: {
                    	 "orderNo" : orderNo
                    	          },
    	             loadComplete:function (data) {
                    	 
                    	console.log('data======',data);
                    	console.log('model.productionDetailInfo11111111111111111111112222222222222222222',model.productionDetailInfo.$model);
                    	for (var i = 0; i < data.length; i++) {
                    		model.initproductionDetailInfo();
                    		console.log('[model.productionDetailInfo]'+i,model.productionDetailInfo);
                    		console.log('data[i].sku',data[i].sku);
                    		console.log('data[i].uuid',data[i].uuid);
                    		model.productionDetailInfo.orderDetailUuid = data[i].uuid;
                    		model.productionDetailInfo.sku = data[i].sku;
                    		model.productionDetailInfo.name = data[i].name;
                    		model.productionDetailInfo.orderNo = data[i].orderNo;
                    		model.productionDetailInfo.model = data[i].model;
                    		model.productionDetailInfo.amount = data[i].quantity;
                    		model.productionDetailInfo.already = data[i].already;
                    		model.productionDetailInfo.alreadyOut = data[i].alreadyOut;
                    		model.productionDetailInfo.goodsUuid = data[i].goodsUuid;
                    		console.log('model.productionDetailInfo',model.productionDetailInfo.$model);
                    		grid_arr.push(model.productionDetailInfo.$model);
                    		console.log('grid_arr',grid_arr); 	  	
						}
                    	
                    	
                    	 
                     },
                     loadError: function (xhr, status, error) {
//                         alert(JSON.parse(xhr.responseText).msg);
                     },
                     colNames : [ 'sku' ,'品名','规格','颜色','总数'],
           		     colModel : [ 
           		                 {name : 'sku',index : 'sku',width : 120,align : "right"} ,
           		                 {name : 'name',index : 'name',width : 180},
           		                 {name : 'model',index : 'model',width : 120,align : "right"}, 
           		                 {name : 'color',index : 'model',width : 120,align : "right"}, 
           		                 {name : 'quantity',index : 'quantity',width : 120,align : "right"} 
           		               ],
                     cmTemplate: {
                     sortable: false,
                     title: false
                     },
//                     page: 1,
//                     rowNum: 10,
//                     rowList: [10, 20, 30],
//                     pager: '#page',
                     sortname: 'id',
                     viewrecords: true,
                     forceFit: false,
                     rownumbers: true,
                     multiselect: true,
                     multiboxonly: true,
                     sortorder: "desc",
                     autoScroll: false,
                     height: 150,
                     altRows: true,
                     gridview: true,
                     autowidth: true,
                     jsonReader: {
                         root: "data.list",
                         records: "data.totalRow",
                         total: "data.totalPage",
                     },
                 });
	            	 model.Issued(rowData);
                
             });
              //订单审核
             $("#examine").on("click",function (e) {
            	  e.preventDefault();
//                   if (Business.verifyRight("BU_DELETE")) {
                  var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                  t.length ? model.examine(t.join()) : parent.Public.tips({
                      type: 2,
                      content: "请选择要审核的订单！"
                  })
             });
             
             // 删除
             $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
            	 var t = $(this).parent().data("id");
            	 var id = $("#grid").jqGrid("getGridParam", "selarrrow");
            	 var rowData = $("#grid").jqGrid('getRowData',id);
            	 if(rowData.productionInstructionStatus == '已下达'){
            		 dialog({
                         title: "错误！",
                         content: "已下达生产任务的订单不能删除！",
                         okValue: "确定",
        	        	 ok: function (){
        	        	 }
                	 }).showModal();
            		 return;  
            	 }else{
                     var ei = [];
                     var e = $(this).parent().data("id");
                     ei.push(e);
                     model.del(e);
            	 }
             });
             $("#search").click(function (e) {
                 e.preventDefault();
                 model.queryData();
             });
             $(".fa-refresh").click(function (e) {
                 e.preventDefault();
                 model.reset();
                 model.queryData();
             })
             $("#btn-batchDel").click(function (e) {
            	 var t = $(this).parent().data("id");
            	 var id = $("#grid").jqGrid("getGridParam", "selarrrow");
            	 var rowData = $("#grid").jqGrid('getRowData',id);
            	 if(rowData.productionInstructionStatus == '已下达'){
            		 dialog({
                         title: "错误！",
                         content: "已下达生产任务的订单不能删除！",
                         okValue: "确定",
        	        	 ok: function (){
        	        	 }
                	 }).showModal();
            		 return;  
            	 }else{
            		 e.preventDefault();
                     // if (Business.verifyRight("BU_DELETE")) {
                     var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                     t.length ? model.del(t.join()) : parent.Public.tips({
                         type: 2,
                         content: "请选择需要删除的项"
                     })
            	 }
             });
         },
         initorder: function () {
             	model.businessListInfo={
	         		id: "",
	                name: "",
	                level: "",
	                areaId: "",
	                describe:"",
	                createTime:"",
	                createUser: ""
             	}
             },
         initproduction:function(){
        	 model.productionInfo= {
         		id:"",
         		uuid:"",
         		productionNo:"",
         		startingDate:"",
         		destination:"",
         		freightForwarding:"",
         		ceva:"",
         		samDepartment:"",
         		qcDepartment:"",
         		productDepartment:"",
         		totalQuantity:"",
         		examination:"",
         		comment:"",
         		orderNo:""
	         }
           },
           initproductionDetailInfo:function(){
        	   model.productionDetailInfo={
               	id:"",
               	uuid:"",
               	sku:"",
               	name:"",
               	orderNo:"",
               	model:"",
               	amount:"",
               	already:"",
               	alreadyOut:"",
               	goodsUuid:"",
               	orderDetailUuid:""
               }
           }
    })
    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
});
